package com.example.cardgame.fragments

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.example.cardgame.R
import com.example.cardgame.model.UserInfo
import com.example.cardgame.databinding.FragmentPersonalInfoBinding
import com.example.cardgame.utils.FileUtils.loadUserInfo
import java.io.ObjectInputStream


class PersonalInfoFragment : Fragment() {
    private var _binding: FragmentPersonalInfoBinding? = null
    private val binding get() = _binding!!
    private val fileName = "user_info.dat"

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _binding = FragmentPersonalInfoBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        val  userInfo = loadUserInfo(requireContext(), fileName) ?: UserInfo("N/A", "N/A", "N/A", "N/A", "N/A", "N/A", 0, 0)
        binding.nameText.text = userInfo.name
        binding.sidText.text = userInfo.sid
        binding.phoneText.text = userInfo.phone
        binding.emailText.text = userInfo.email
        binding.genderText.text = userInfo.gender
        binding.hobbyText.text = userInfo.hobby
        binding.score2Text.text = userInfo.score2.toString()
        binding.score3Text.text = userInfo.score3.toString()

        binding.buttonEdit.setOnClickListener {
            parentFragmentManager.beginTransaction()
                .replace(R.id.fragment_container, EditFragment())
                .addToBackStack(null)
                .commit()
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

//    private fun loadUserInfo(): UserInfo?{
//        return try {
//            val fileInputStream = requireContext().openFileInput(fileName)
//            val objectInputStream = ObjectInputStream(fileInputStream)
//            val userInfo = objectInputStream.readObject() as UserInfo
//            objectInputStream.close()
//            userInfo
//        } catch (e: Exception) {
//            e.printStackTrace()
//            null
//        }
//    }
}